package com.longqin.wechat.config;

import java.lang.reflect.AnnotatedElement;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.alibaba.fastjson.JSON;
import com.longqin.wechat.annotation.KeepOriginal;
import com.longqin.wechat.entity.BaseResponse;
import com.longqin.wechat.entity.ResponseData;
import com.longqin.wechat.util.ResponseEnum;

/**
 * @Description: 对返回的结果进行封装
 * @Author longqin
 * @Date 2025-05-08
 * 
 */
@EnableWebMvc
@Configuration
@RestControllerAdvice(basePackages = "com.longqin.wechat.controller")
public class CommonResultResponseAdvice implements ResponseBodyAdvice<Object> {
    
	/**
     * 对没加KeepOriginal注解的controller方法进行结果集封装
     * **/
	@Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    	AnnotatedElement annotatedElement =returnType.getAnnotatedElement();
    	KeepOriginal ko= AnnotationUtils.findAnnotation(annotatedElement, KeepOriginal.class);
        return null==ko;
    }

    /**
     * 对controller的返回结果集进行统一封装
     * **/
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, 
    		Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    	if (body instanceof BaseResponse) {
        	  return body;
        }
    	if(body instanceof String){
		    String str  = JSON.toJSONString(new ResponseData<>(ResponseEnum.SUCCESS.getCode(), "SUCCESS", body));
		    return str;
		}
        return new ResponseData<>(ResponseEnum.SUCCESS.getCode(), "SUCCESS", body);
     }
}

